package com.lsx.logisticscore.entity;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lsx.logisticscore.mapper.AccountMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

/**
 * @Author: Liang
 * @Date: 2021/12/26
 * @Description:
 */
public class AccountRealm extends AuthorizingRealm {
    @Autowired
    private AccountMapper accountMapper;
    /**
     * 此处实现授权逻辑
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//        //获取到用户名
//        String username = (String) SecurityUtils.getSubject().getPrincipal();
//
//        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//        Set<String> set = new HashSet<>();
//        set.add("user:admin");
//        set.add("user:show");
//        info.setStringPermissions(set);

//        return info;
        return null;
    }


    /**
     * 此处实现认证逻辑
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        //取出输入的用户名和密码
        String empId = (String) authenticationToken.getPrincipal();
        String password = new String((char[]) authenticationToken.getCredentials());

        //从数据库中取出数据
        QueryWrapper<Account> wrapper = new QueryWrapper<>();
        wrapper.eq("emp_id", empId);
        Account account = accountMapper.selectOne(wrapper);

        //没有查到用户
        if (null == account){
            return null;
//            throw new AccountException("用户不存在");

        }


        //自动判断密码是否匹配
        return new SimpleAuthenticationInfo(empId,account.getPassword(), ByteSource.Util.bytes(account.getEmpId()), getName());
    }

    //写在这是干嘛的

    public String md5Pwd(String empId, String password){
        String md5Pwd = new SimpleHash("MD5", password,
                ByteSource.Util.bytes(empId), 2).toHex();
        return md5Pwd;
    }
}
